package com.md.value.html;

import com.google.common.collect.Lists;
import com.md.model.html.LabelStyle;
import com.md.util.POIUtil;
import lombok.Getter;
import org.openxmlformats.schemas.wordprocessingml.x2006.main.CTInd;
import org.openxmlformats.schemas.wordprocessingml.x2006.main.CTPPrGeneral;
import org.openxmlformats.schemas.wordprocessingml.x2006.main.CTSpacing;

import java.util.List;
import java.util.Optional;

import static com.md.util.POIUtil.getMargin;
import static com.md.util.POIUtil.getSpacing;

/**
 * @author 刘骄阳
 * 2024-06-14 18:38
 */
@Getter
public class Position {
  private LabelStyle marginLeft;
  private LabelStyle marginRight;
  private LabelStyle marginTop;
  private LabelStyle marginBottom;
  /**
   * 首行缩进
   */
  private LabelStyle firstLineIndent;

  /**
   * 水平对齐方式
   */
  private LabelStyle alignment;

  private LabelStyle backgroundColor;

  public Position(final CTPPrGeneral ctpPrGeneral) {
    getMargin(ctpPrGeneral, CTInd::xgetLeft).ifPresent(size ->
      marginLeft = LabelStyle.of(LabelStyleType.MARGIN_LEFT, Unit.DXA.convert(Unit.PX, size.doubleValue()), Unit.PX));
    getMargin(ctpPrGeneral, CTInd::xgetRight).ifPresent(size ->
      marginRight = LabelStyle.of(LabelStyleType.MARGIN_RIGHT, Unit.DXA.convert(Unit.PX, size.doubleValue()), Unit.PX));
    getMargin(ctpPrGeneral, CTInd::xgetFirstLine).ifPresent(size ->
      firstLineIndent = LabelStyle.of(LabelStyleType.TEXT_INDENT, Unit.DXA.convert(Unit.PX, size.doubleValue()), Unit.PX));

    getSpacing(ctpPrGeneral, CTSpacing::xgetBefore).ifPresent(size ->
      marginTop = LabelStyle.of(LabelStyleType.MARGIN_TOP, Unit.DXA.convert(Unit.PX, size.doubleValue()), Unit.PX));
    getSpacing(ctpPrGeneral, CTSpacing::xgetAfter).ifPresent(size ->
      marginBottom = LabelStyle.of(LabelStyleType.MARGIN_BOTTOM, Unit.DXA.convert(Unit.PX, size.doubleValue()), Unit.PX));

    POIUtil.getAlignment(ctpPrGeneral).ifPresent(textAlign -> alignment = textAlign);

    Optional.ofNullable(ctpPrGeneral.getShd()).ifPresent(ctShd ->
      backgroundColor = LabelStyle.of(LabelStyleType.BACKGROUND_COLOR,
        "#" + POIUtil.getColor(ctShd.xgetColor(), ColorIndex.WHITE.getHex())));
  }

  public List<LabelStyle> getLabelStyle() {
    List<LabelStyle> labelStyles = Lists.newArrayList();
    Optional.ofNullable(marginLeft).ifPresent(labelStyles::add);
    Optional.ofNullable(marginRight).ifPresent(labelStyles::add);
    Optional.ofNullable(marginTop).ifPresent(labelStyles::add);
    Optional.ofNullable(marginBottom).ifPresent(labelStyles::add);
    Optional.ofNullable(firstLineIndent).ifPresent(labelStyles::add);
    Optional.ofNullable(alignment).ifPresent(labelStyles::add);
    return labelStyles;
  }

}
